package cfdt.tools.crypto;

import cfdt.common.enums.CommonCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cfca.sadk.lib.crypto.JCrypto;
import cfdt.common.exception.CodeException;
import cfdt.tools.util.StringUtils;

/**
 * <pre>
 * Modify Information:
 * Author       Date        Description
 * ============ =========== ============================
 * zhangxing    2009-03-20  Create this file
 * shilei       2015-07-22  增加对签名算法SHA256withRSA的支持
 *
 * </pre>
 */
public class SecurityUtils {

    private final static Logger logger = LoggerFactory.getLogger(SecurityUtils.class);

    private static SecurityUtils instance = new SecurityUtils();

    public static SecurityUtils getInstance() {
        return instance;
    }

    public SecurityUtils() {
        try {
            JCrypto.getInstance().initialize(JCrypto.JSOFT_LIB, null);
        } catch (Exception e) {
            throw new CodeException(CommonCodeEnum.CODE_0009);
        }
    }

    // 这里SM4默认加密密钥还是使用原CPCN的，本想换成CFDT，但是我们使用的测试小工具还是CPCN，如果改了就不方便了
    private static final String SM4PW = "Cpcn1234#";

    /**
     * <p>sm4解密</p>
     *
     * @param cipherText
     * @return
     * @throws CodeException
     * @author chenchao
     * @date 2021-03-11
     */
    public static String decryptSM4(String cipherText) throws CodeException {
        String plainText = "";
        if (StringUtils.isNotEmpty(cipherText)) {
            try {
                plainText = SM4Util.decrypt(cipherText, SM4PW);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new CodeException(CommonCodeEnum.CODE_2001);
            }
        }
        return plainText;
    }

    /**
     * <p>sm4加密</p>
     *
     * @param plainText
     * @return
     * @throws CodeException
     * @author chenchao
     * @date 2021-03-11
     */
    public static String encryptSM4(String plainText) throws CodeException {
        String cipherText = "";
        if (StringUtils.isNotEmpty(plainText)) {
            try {
                cipherText = SM4Util.encrypt(plainText, SM4PW);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new CodeException(CommonCodeEnum.CODE_2002);
            }
        }
        return cipherText;
    }

}
